package gold.digger;

import gold.vo.TreeNode;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC337 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {


        public int rob(TreeNode root) {
            int[] result = robInternal(root);
            return Math.max(result[0], result[1]);
        }

        public int[] robInternal(TreeNode root) {
            if (root == null) return new int[2];
            int[] result = new int[2];

            int[] left = robInternal(root.left);
            int[] right = robInternal(root.right);

            result[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
            result[1] = left[0] + right[0] + root.val;

            return result;
        }


        public Map<TreeNode, Integer> chooseMap = new HashMap<>();
        public Map<TreeNode, Integer> notChooseMap = new HashMap<>();

        public int rob_Pass_Slow(TreeNode root) {
            return Math.max(robRecur(root, true), robRecur(root, false));
        }

        public int robRecur(TreeNode root, boolean choose) {
            if (null == root) return 0;
            if (choose && chooseMap.containsKey(root)) return chooseMap.get(root);
            if (!choose && notChooseMap.containsKey(root)) return notChooseMap.get(root);

            int curMax = -1;
            if (choose) {
                curMax = root.val + robRecur(root.left, false) + robRecur(root.right, false);
                chooseMap.put(root, curMax);
                return curMax;
            }

            int c11 = robRecur(root.left, true) + robRecur(root.right, true);
            int c00 = robRecur(root.left, false) + robRecur(root.right, false);
            int c10 = robRecur(root.left, true) + robRecur(root.right, false);
            int c01 = robRecur(root.left, false) + robRecur(root.right, true);
            curMax = Math.max(c11, Math.max(c00, Math.max(c01, c10)));
            notChooseMap.put(root, curMax);
            return curMax;
        }
    }

    public void run() {
        Solution solution = new Solution();
        TreeNode root = TreeNode.createTree("[2,1,3,null,4]");
        System.out.println(solution.rob(root));
    }

    public static void main(String[] args) throws Exception {
        LC337 an = new LC337();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}

